package code.structure.module.scene.view.iso
{
	import code.main.AppData;
	import code.structure.manager.bitmap.MaterialBitmapCoverManager;
	import code.structure.module.configs.data.ItemConfigData;
	import code.structure.module.scene.model.data.SceneItemData;
	import code.structure.module.scene.view.YIsoWorld;
	import code.tools.bitmap.MovieBitMap;
	import code.tools.bitmap.MoviePlayer;
	import code.tools.method.CommonMethod;
	import code.untils.ColorTransformEnum;
	import code.untils.FiltersEnum;
	import code.untils.IsoStatusConst;
	import code.untils.ItemTypeConst;
	import code.untils.SceneConfig;
	
	import com.patience.map.isometric.core.IsoGrid;
	import com.patience.map.isometric.iso.IsoObject;
	import com.patience.utils.FilterUtil;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.geom.Vector3D;
	
	/**
	 *项目的世界元素基类 
	 * 做一步改进 不管有没有动画都有movieplayer
	 * @author Yuri
	 * 
	 */
	public class YIsoObject extends IsoObject
	{
		protected var _data:SceneItemData;
		private var _id:String;
		
		protected var _bitmapList:Array;
		
		private var _status:String;
		
		private var _originalPoint3D:Vector3D;
		/**
		 *格子信息 
		 */
		private var _gridShape:Shape;
		
		/**
		 *动画帧频 
		 */
		protected var animationFrame:int = 30;
		
		protected var _direction:int = 1;
		protected var _supportMaxDirection:int = 2;
		/**
		 *主体容器 
		 */
		protected var _mainBitMapContainer:Sprite;
		
		protected var _isMaterialLoadComplete:Boolean = false;
		
		private var _mouseTipEnable:Boolean;
		
		private var _frameSumCount:int;
		
		/**
		 *是否需要延迟动画播放间隔 
		 */
		protected var _isNeedDelayIntervelAnimation:Boolean = true;
		
		/**
		 *tip 自身tip
		 */
		protected var _tip:*;
		/**
		 *指引tip 
		 */
		protected var _guideTip:*;
		
		private var _selfTipEnable:Boolean = false;
		
		private var _isMoving:Boolean;
				
		protected var _isGuide:Boolean;
		/**
		 *是否改变了外观 
		 */
		protected var _isChangeFacade:Boolean =true;
		/**
		 *已经绘制好检测碰撞的世界场景尺寸 
		 */
		protected var _createHitBitmapDataWorldScale:Number = 1;
		/**
		 *原始对象通道 
		 */
		private var _originalColorTransform:ColorTransform;
		
		/**
		 *是否拥有额外的动画 
		 */
		protected var _isHadExtraAnimation:Boolean;
		/**
		 *是否拥有本身的动画 
		 */
		protected var _isBodyAnimation:Boolean;
		/**
		 *动画位图 
		 */
		protected var _animationBitmap:MovieBitMap;
		
		/**
		 *是否在播放动画状态 
		 */
		protected var _isPlayAnimationStatus:Boolean;
		/**
		 *是否需要相应鼠标 
		 */
		private var _isResponseMouse:Boolean = true;
		/**
		 *鼠标相应区域 
		 */
		protected var _mouseResponseBody:Sprite;
		
		protected var _isCanDiy:Boolean = true;
		public function YIsoObject()
		{
			_mouseResponseBody = new Sprite();
			addChild(_mouseResponseBody);
			_mainBitMapContainer = new Sprite();
			_mouseResponseBody.addChild(_mainBitMapContainer);
			
			mouseEnabled = false;
			mouseChildren = false;
			
			initEnable();
		}
		
		protected function initEnable():void{
			clickEnabled = true;
			mouseMoveEnabled = true;
		}
		
		protected function refresh():void{
			_id = data.id;
			//这里只做刷新素材
			floorXCount = data.data.sizeX;
			floorZCount = data.data.sizeZ;
			
			/*if(data.data.itemType == ItemTypeConst.CORNER_WALL || data.data.itemType == ItemTypeConst.FENCE || data.data.itemType == ItemTypeConst.SUNK_FENCE){ //支持四方向
				_supportMaxDirection = 4;
				_isBodyAnimation = false;
			}*/
			direction = data.direction;
			clear();
			refreshMaterial(data.data.sPath,SceneConfig.SCENE_CLASS_NAME);
		}
		
		/**
		 *刷新素材 
		 * 
		 */
		protected function refreshMaterial(path:String,subKey:String):void{
			isMaterialLoadComplete = false;
			MaterialBitmapCoverManager.getInstance().getMaterial(path,subKey,onCovertCompleteFun);
		}
		
		/**
		 *转换成位图回调 
		 * @param subKey
		 * @param bitmapArr
		 * 
		 */
		protected function onCovertCompleteFun(bitmapArr:Array):void
		{
			isMaterialLoadComplete = true;
			_bitmapList = bitmapArr;
			frameSumCount = _bitmapList.length;
			if(frameSumCount>0)
				verticalHeight = _bitmapList[0][1];
			mainBodyLoadCompleteNext();
		}
		
		/**
		 *主体加载完成后函数 
		 * 
		 */
		protected function mainBodyLoadCompleteNext():void{
			if(_isBodyAnimation){
				createAnimation(_bitmapList,animationFrame);
			}else{
				if(supportMaxDirection == 4){
					jumpToFrame(direction);
				}else{
					jumpToFrame(1);
				}
			}
		}
		
		public function initBuildCallFun():void{
			if(data) data.status = 4;
		}
		
		/**
		 *数据 
		 * @return 
		 * 
		 */
		public function get data():SceneItemData
		{
			return _data;
		}
		
		public function set data(value:SceneItemData):void
		{
			_data = value;
			if(value){
				id = value.id;
				refresh();
			}
		}
		
		public function get id():String
		{
			return _id;
		}
		
		public function set id(value:String):void
		{
			_id = value;
		}
		
		
		/**
		 * @public
		 */
		override public function set isUnlock(value:Boolean):void
		{
			if(isUnlock == value) return;
			super.isUnlock = value;
			status =  isUnlock?IsoStatusConst.ISO_STATUS_NORMAL:IsoStatusConst.ISO_STATUS_LOCKED;
			if(isUnlock){ 
				initEnable();
				showTip();
			}else{
				removeTip();
			}
			if(_isBodyAnimation) isUnlock?playAnimation():pauseAnimation();
			refreshEnable();
		}
		
		
		/**
		 * @private
		 */
		override public function set areaIndex(value:String):void
		{
			super.areaIndex = value;
		}
		
		/**
		 *状态 比如 正常 鼠标overout等
		 */
		public function set status(value:String):void
		{
			if(!_mainBitMapContainer) return;
			if(_status==value && value !=IsoStatusConst.ISO_STATUS_NORMAL) return;
			_status = value;
			if(!_originalColorTransform) _originalColorTransform = this.transform.colorTransform;
			switch(value){
				case IsoStatusConst.ISO_STATUS_NORMAL:
						_mainBitMapContainer.filters = [];
						if(!isUnlock){
							_mainBitMapContainer.transform.colorTransform = ColorTransformEnum.blackColorTransform;
							_mainBitMapContainer.filters = [FiltersEnum.getColorMatrixFilter(-11,-13,0,15)];
						}else{
							_mainBitMapContainer.transform.colorTransform = _originalColorTransform;
						}
						this.alpha = 1;
						if(_mainBitMapContainer)_mainBitMapContainer.alpha = 1;
					break;
				case IsoStatusConst.ISO_STATUS_OVER:
					if(!isUnlock){
						_mainBitMapContainer.transform.colorTransform = _originalColorTransform;
					}
					_mainBitMapContainer.filters = [FilterUtil.yellowGlowFilter];
					_mainBitMapContainer.alpha = .6;
					break;
				case IsoStatusConst.ISO_STATUS_DISABLE_PLACE:
					diyAble(false);
					break;
				case IsoStatusConst.ISO_STATUS_ABLE_PLACE:
					diyAble();
					break;
				case IsoStatusConst.ISO_STATUS_FRIEND_HELP_OVER:
					_mainBitMapContainer.filters = [FiltersEnum.greenGlowFilter];
					break;
				case IsoStatusConst.ISO_STATUS_LOCKED:
					_mainBitMapContainer.transform.colorTransform = ColorTransformEnum.blackColorTransform;
					break;
			}
		}
		
		/**
		 *是否显示格子 
		 * @param isShow
		 * 
		 */
		public function showGrid(isShow:Boolean = true):void{
			if(isShow){
				//				if(_gridShape && contains(_gridShape)) return;
				if(_gridShape){
					_gridShape.graphics.clear();
				}
				_gridShape  = IsoGrid.drawGridShape(floorXCount,floorZCount,size);
				
				_gridShape.x -= offsetX ;
				_gridShape.y -= offsetY - 4;
				addChildAt(_gridShape,0);
			}else{
				if(_gridShape && contains(_gridShape)) removeChild(_gridShape);
			}
		}
		
		/**
		 * 是否可以diy
		 * @param isAble
		 * 
		 */
		private function diyAble(isAble:Boolean=true):void{
			if(_gridShape && contains(_gridShape)){
				var colortra:ColorTransform = _gridShape.transform.colorTransform;
				colortra.color = isAble?0x00ff00:0xff0000;
				_gridShape.transform.colorTransform = colortra;
				this.alpha = isAble?1:.5;
			}
		}
		
		/**
		 *跳帧 给不需要动画时候使用 (主体使用)
		 * @param frame
		 * 
		 */
		protected function jumpToFrame(frame:int):void{
			if(_isBodyAnimation) return;
			removeMotionListener();
			clearAnimation();
			createBody();
			if(frameSumCount>0 && frame<=frameSumCount && _bitmap){
				//_isChangeFacade = true;
				frame -=1;
				_bitmap.x = offsetX + _bitmapList[frame][0];
				_bitmap.y = offsetY + _bitmapList[frame][1];
				_bitmap.bitmapData = _bitmapList[frame][2];
			}
		}
		
		/**
		 *创建 MoviePlayer
		 * @param bmap
		 * @param dataList
		 * @param bX
		 * @param bY
		 * @param interval
		 * 
		 */
		/*protected function createMoviePlayer(bmap:Bitmap,dataList:Array=null,interval:int=33,bX:Number=0,bY:Number=0):void{
		if(_mainPlayer) return;
		_mainPlayer = new MoviePlayer(bmap,dataList,bX,bY,interval);
		}*/
		
		/**
		 *原始正常可以在世界中的坐标(为防止diy时候回退) 
		 */
		public function get originalPoint3D():Vector3D
		{
			return _originalPoint3D;
		}
		
		/**
		 * @private
		 */
		public function set originalPoint3D(value:Vector3D):void
		{
			_originalPoint3D = value;
		}
		
		/**
		 *方向 顺时针增加 
		 */
		public function get direction():int
		{
			return _direction;
		}
		
		/**
		 * @private
		 */
		public function set direction(value:int):void
		{
			if(direction == value) return;
			_direction = value%(supportMaxDirection+1) || 1;
			if(supportMaxDirection == 2){
				var isEqualSize:Boolean = this.floorXCount == this.floorZCount;
				if(!isEqualSize && parentWorld && !isMoving) parentWorld.removeIsoObjectMapInfo(this);
				if(direction==1){
					_mainBitMapContainer.scaleX = 1;
					this.floorXCount = data.data.sizeX;
					this.floorZCount = data.data.sizeZ;
				}else{
					_direction = 2;
					_mainBitMapContainer.scaleX = -1;
					this.floorXCount = data.data.sizeZ;
					this.floorZCount = data.data.sizeX;
				}
				if(!isEqualSize && parentWorld && !isMoving) parentWorld.addIsoObjectMapInfo(this);
			}else if(supportMaxDirection == 4){
				jumpToFrame(direction);
			}
			isChangeFacade = true;
		}
		
		/**
		 *添加动画监听 
		 * 
		 */
		protected function addMotionListener():void{
			/*if(_isNeedDelayIntervelAnimation && _mainPlayer && !_mainPlayer.hasEventListener(MoviePlayer.PLAY_COMP))
			_mainPlayer.addEventListener(MoviePlayer.PLAY_COMP,onMotionCircleOverHandler);*/
			if(_isNeedDelayIntervelAnimation && _animationBitmap && !_animationBitmap.hasEventListener(MoviePlayer.PLAY_COMP))
				_animationBitmap.addEventListener(MoviePlayer.PLAY_COMP,onMotionCircleOverHandler);
		}
		
		protected function onMotionCircleOverHandler(event:Event):void
		{
		}
		
		/**
		 *移除动画监听 
		 * 
		 */
		protected function removeMotionListener():void{
			/*if(_mainPlayer && _mainPlayer.hasEventListener(MoviePlayer.PLAY_COMP))
			_mainPlayer.removeEventListener(MoviePlayer.PLAY_COMP,onMotionCircleOverHandler);*/
			if(_animationBitmap && _animationBitmap.hasEventListener(MoviePlayer.PLAY_COMP))
				_animationBitmap.removeEventListener(MoviePlayer.PLAY_COMP,onMotionCircleOverHandler);
		}
		
		
		/**
		 *创建tip 
		 * 
		 */
		protected function createTip():void{
			if(!selfTipEnable) return;
			if(!AppData.isMyScene &&  data.status!=4) return;
			removeTip(true);
			/*_tip = new ProdTips(this,BaseTips.TIPS_LAYER_TYPE_SCENE);*/
			showTip();
		}
		
		/**
		 *显示tip (正常tip不包含 指引型)
		 * 
		 */
		public function showTip():void{
			
			if(isUnlock && _tip && parentWorld && (parentWorld as YIsoWorld).status == SceneConfig.SCENE_NORMAL){
				_tip.show(this);
				if(_guideTip && contains(_guideTip)) this.addChild(_guideTip);
				_isChangeFacade = true;
			}
		}
		
		/**
		 *隐藏tip 
		 * 
		 */
		/*public function hiddenTip():void{
		if(_tip && _tip.parent){
		_tip.alpha = 0;
		}
		}*/
		
		/**
		 *移除tip是否完全移除 
		 * @param isClear
		 * 
		 */
		public function removeTip(isClear:Boolean = false):void{
			if(_tip && _tip.parent){
				_tip.close();
				_isChangeFacade = true;
			}
			if(_tip && isClear) _tip = null;
		}
		
		/**
		 *检测碰撞 
		 * @param x
		 * @param y
		 * @return 
		 * 
		 */
		override public function hitTest(x:Number,y:Number):DisplayObject
		{
			if(!this.parentWorld || !_mainBitMapContainer){
				return null;
			}	
			if(!_isChangeFacade && _createHitBitmapDataWorldScale !=this.parentWorld.scale){
				_isChangeFacade = true;
			}
			if(bitmapData){
				if(Math.abs(bitmapData.width-this.width)>3 || Math.abs(bitmapData.height-this.height)>3){
					_isChangeFacade = true;
				}
			}
			if(!bitmapData || _isChangeFacade){
				bitmapData = drawBitmapData(/*_mouseResponseBody*/this);
				_isChangeFacade = false;
				_createHitBitmapDataWorldScale =this.parentWorld.scale;	
			}
			if(bitmapData)
			{
				var r:Rectangle = this.getRect(this);
				var $point:Point = this.localToGlobal(new Point(r.left,r.top));
				if(bitmapData.hitTest($point,0x00,new Point(x,y)))
				{
					return this;
				}
			}
			return null;
		}
		
		/**
		 *绘制位图数据 (后期看是否可以优化)
		 * @param dis
		 * @return 
		 * 
		 */
		/*public  function drawBitmapData(dis:DisplayObject):BitmapData{
		var rectangle:Rectangle = dis.getRect(dis);
		var bWidth:Number = (dis.width<1)?1:dis.width;
		var bHeight:Number =(dis.height<1)?1:dis.height;
		var bitmapD:BitmapData = new BitmapData(bWidth*parentWorld.scale,bHeight*parentWorld.scale,true, 0x00);
		
		bitmapD.draw(dis,new Matrix(dis.scaleX*parentWorld.scale,0,0,dis.scaleY*parentWorld.scale,
		-rectangle.x*dis.scaleX*parentWorld.scale,-rectangle.y*dis.scaleY*parentWorld.scale));
		return bitmapD;
		}*/
		public  function drawBitmapData(dis:DisplayObject):BitmapData{
			var rectangle:Rectangle = dis.getRect(dis);
			var bWidth:Number = (dis.width*parentWorld.scale<1)?1:dis.width;
			var bHeight:Number =(dis.height*parentWorld.scale<1)?1:dis.height;
			var bitmapD:BitmapData = new BitmapData(bWidth,bHeight/*bWidth*parentWorld.scale,bHeight*parentWorld.scale*/,true, 0x00);
			
			bitmapD.draw(dis,new Matrix(dis.scaleX*parentWorld.scale,0,0,dis.scaleY*parentWorld.scale,
				-rectangle.x*dis.scaleX*parentWorld.scale,-rectangle.y*dis.scaleY*parentWorld.scale));
			return bitmapD;
		}
		
		/**
		 *最多支持几个方向
		 */
		private function get supportMaxDirection():int
		{
			return _supportMaxDirection;
		}
		
		/**
		 * @private
		 */
		private function set supportMaxDirection(value:int):void
		{
			_supportMaxDirection = value;
		}
		
		/**
		 *素材加载是否完成 
		 */
		protected function get isMaterialLoadComplete():Boolean
		{
			return _isMaterialLoadComplete;
		}
		
		/**
		 * @private
		 */
		protected function set isMaterialLoadComplete(value:Boolean):void
		{
			_isMaterialLoadComplete = value;
		}
		
		/**
		 *是否接受鼠标移上去tip 
		 */
		public function get mouseTipEnable():Boolean
		{
			return _mouseTipEnable;
		}
		
		/**
		 * @private
		 */
		public function set mouseTipEnable(value:Boolean):void
		{
			_mouseTipEnable = value;
		}
		
		/**
		 *帧频总数 
		 */
		public function get frameSumCount():int
		{
			return _frameSumCount;
		}
		
		/**
		 * @private
		 */
		public function set frameSumCount(value:int):void
		{
			_frameSumCount = value;
		}
		
		/**
		 * 激活解锁（物品建造完成可以进行生产） 
		 * 
		 */
		public function unlockCallFun():void{
			data.energy = 0;
			data.status = 4;
		}
		
		/**
		 *自身tip是否需要 
		 */
		public function get selfTipEnable():Boolean
		{
			return _selfTipEnable;
		}
		
		/**
		 * @private
		 */
		public function set selfTipEnable(value:Boolean):void
		{
			_selfTipEnable = value;
		}
		
		/**
		 *是否在移动 
		 */
		public function get isMoving():Boolean
		{
			return _isMoving;
		}
		
		/**
		 * @private
		 */
		public function set isMoving(value:Boolean):void
		{
			if(_isMoving == value) return;
			_isMoving = value;
			if(parentWorld){
				_isMoving?parentWorld.removeIsoObjectMapInfo(this):parentWorld.addIsoObjectMapInfo(this);
			}
		}
		
		/**
		 *升级 
		 * @param d
		 * 
		 */
		public function upgrade(d:ItemConfigData):void{
			
		}
		
		/**
		 *是否可以升级 
		 */
		public function get isCanUpgrade():Boolean
		{
			return false;
		}
		
		/**
		 *是否引导 
		 */
		public function get isGuide():Boolean
		{
			return _isGuide;
		}
		
		/**
		 * @private
		 */
		public function set isGuide(value:Boolean):void
		{
			_isGuide = value;
			if(value){
				/*if(!_guideTip)_guideTip = new GoTips();
				this.addChild(_guideTip);
				_guideTip.show();*/
			}else{
				if(_guideTip && contains(_guideTip)){
					this.removeChild(_guideTip);
					_guideTip.destroy();
					_guideTip = null;
				}
			}
		}
		
		/**
		 *是否改变了外观 
		 */
		public function set isChangeFacade(value:Boolean):void
		{
			_isChangeFacade = value;
		}
		
		/**
		 *更新场景状态 
		 * 
		 */
		public function refreshIsoWorldStatus(wStatus:String):void{
			switch(wStatus){
				case SceneConfig.SCENE_NORMAL:
					showTip();
					break;
				case SceneConfig.SCENE_DIY:
					removeTip();
					break;
			}
			refreshEnable();
		}
		
		/**
		 *更新鼠标响应属性 
		 * 未解锁的不可以有鼠标事件（默认情况下）
		 */
		public function refreshEnable():void{
		}
		
		/**
		 *创建主体 
		 * 
		 */
		protected function createBody():void{
			if(!_mainBitMapContainer) return;
			_isChangeFacade = true;
			if(!_bitmap) _bitmap = new Bitmap(null,"auto",true);
			if(!_mainBitMapContainer.contains(_bitmap)) _mainBitMapContainer.addChild(_bitmap);
		}
		
		/**
		 *创建动画 (包含所有类型动画)
		 * @param v
		 * @param frame
		 * 
		 */
		protected function createAnimation(v:Array,frame:int=24):void{
			if(!_mainBitMapContainer) return;
			clearBody();
			_isChangeFacade = true;
			if(!_animationBitmap) _animationBitmap = new MovieBitMap(frame);
			if(!_mainBitMapContainer.contains(_animationBitmap)) _mainBitMapContainer.addChild(_animationBitmap);
			_animationBitmap.bitmapDataList = v;
			_animationBitmap.moviePlayer.goToAndPlay(1);
			_isNeedDelayIntervelAnimation?addMotionListener():removeMotionListener();
			
			if(!isUnlock)_animationBitmap.moviePlayer.goToAndStop(1);
			//清空当前主体对象
			_isPlayAnimationStatus = true;
		}
		
		
		/**
		 *清除主体静止素材 
		 * 
		 */
		protected function clearBody():void{
			if(_bitmap){
				_bitmap.bitmapData = null;
				if(_mainBitMapContainer.contains(_bitmap)){
					_mainBitMapContainer.removeChild(_bitmap);
				}
			}
			_bitmap = null;
		}
		
		/**
		 *清除动画 
		 * 
		 */
		protected function clearAnimation():void{
			removeMotionListener();
			if(_animationBitmap){
				_animationBitmap.destroy();
				if(_mainBitMapContainer.contains(_animationBitmap)){
					_mainBitMapContainer.removeChild(_animationBitmap);
				}
			}
			_animationBitmap = null;
			_isPlayAnimationStatus = false;
		}
		
		/**
		 *暂停动画 
		 * 
		 */
		protected function pauseAnimation(index:int=-1):void{
			if(_animationBitmap){
				if(index<1)
					_animationBitmap.moviePlayer.pause();
				else
					_animationBitmap.moviePlayer.goToAndStop(index);
			}
		}
		
		/**
		 *继续动画 
		 * 
		 */
		protected function playAnimation():void{
			if(_animationBitmap) _animationBitmap.moviePlayer.play();
		}
		
		
		override public function destroy():void{
			clear();
			_mainBitMapContainer = null;
			_mouseResponseBody = null;
			super.destroy();
		}
		
		/**
		 *清空加载的素材 
		 * 
		 */
		protected function clear():void{
			
			clearAnimation();
			clearBody();
			_bitmapList = [];
			removeTip(true);
			isGuide = false;
		}
		
		/**
		 *是否相应鼠标事件操作 
		 */
		public function get isResponseMouse():Boolean
		{
			return _isResponseMouse;
		}
		
		/**
		 * @private
		 */
		public function set isResponseMouse(value:Boolean):void
		{
			_isResponseMouse = value;
		}

		/**
		 *是否支持diy 
		 */
		public function get isCanDiy():Boolean
		{
			return _isCanDiy;
		}

		public function set isCanDiy(value:Boolean):void
		{
			_isCanDiy = value;
			refreshEnable();
		}

		public function get level():int{
			/*return data?0:data.data.iLevel;*/
			return 1;
		}
		
	}
}